<!--
 * @author hemengxia
 * @desc 创建--红包活动
-->
<template>
  <section class="red-packet-activity-manage">
    <div class="manage-title">新建/编辑活动红包配置</div>

    <section class="manage-main">
      <el-form
        ref="form"
        v-loading="formloading"
        :model="form"
        :rules="rules"
        label-width="250px"
        class="main-form"
      >
        <el-form-item label="活动名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动类型" prop="activityType">
          <el-select v-model="form.activityType" placeholder="请选择活动类型" clearable :style="{width:'100%'}">
            <el-option
              v-for="(item, index) in dict.REDPACT"
              :key="index"
              :label="item.dictName"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动起止时间" prop="time">
          <el-date-picker
            v-model="form.time"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            clearable
            :style="{width:'100%'}"
            type="datetimerange"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="封面图" prop="coverId">
          <image-upload
            :key="uploadImg.imagecropperKey"
            v-model="form.coverId"
            :preview-id="uploadImg.viewId"
            :forever="true"
            :width="702"
            :view="uploadImg.view"
            :height="310"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
          />
        </el-form-item>
        <el-form-item label="红包总份数" prop="totalCopies">
          <el-input-number
            v-model="form.totalCopies"
            :min="1"
            :max="999999999"
            :step="1"
            :disabled="checkForm.totalCopies"
            step-strictly
            label="请输入红包总份数"
          />
          <el-checkbox v-model="checkForm.totalCopies" style="margin-left: 30px;">不限制</el-checkbox>
        </el-form-item>

        <el-form-item
          label="每次最小金额(元)"
          prop="onceAmountMini"
        >
          <el-input-number
            v-model="form.onceAmountMini"
            :min="0"
            :max="999999999"
            :precision="2"
            :step="0.01"
            step-strictly

            label="请输入每次最小金额"
          />
        </el-form-item>
        <el-form-item
          label="每次最大金额(元)"
          prop="onceAmountMax"
        >
          <el-input-number
            v-model="form.onceAmountMax"
            :min="0"
            :max="999999999"
            :precision="2"
            :step="0.01"
            step-strictly
            :disabled="checkForm.onceAmountMax"
            label="请输入每次最大金额"
          />
          <el-checkbox v-model="checkForm.onceAmountMax" style="margin-left: 30px;">与最小金额一致</el-checkbox>
        </el-form-item>
        <el-form-item label="红包领取的失效时间(天)" prop="receiveExpiresDatetime">
          <el-input-number
            v-model="form.receiveExpiresDatetime"
            :min="0"
            :max="999999999"
            :step="1"
            step-strictly
            :disabled="checkForm.receiveExpiresDatetime"
            label="请设置红包领取的失效时间"
          />
          <el-checkbox v-model="checkForm.receiveExpiresDatetime" style="margin-left: 30px;">不限制</el-checkbox>
        </el-form-item>
        <el-form-item label="红包最终失效时间" prop="lastExpiresDatetime">
          <el-date-picker
            v-model="form.lastExpiresDatetime"
            type="datetime"
            placeholder="选择时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :disabled="checkForm.lastExpiresDatetime"
          />
          <el-checkbox v-model="checkForm.lastExpiresDatetime" style="margin-left: 30px;">不限制</el-checkbox>
        </el-form-item>
        <section class="join-conditions-content">
          <p class="title">参与条件设置</p>
          <el-form-item label="是否限制用户" prop="limitUser">
            <el-radio-group v-model="form.limitUser" :disabled="isDisableStatus.limitUser">
              <el-radio :label="0">按条件限制</el-radio>
              <el-radio :label="1">按用户清单限制（活动创建成功后，通过“参与人员”菜单维护用户清单）</el-radio>
            </el-radio-group>

          </el-form-item>
          <el-form-item
            v-if="form.limitUser ==0 "
            label="是否需要认证"
            prop="limitAuth"
          >
            <el-radio-group v-model="form.limitAuth">
              <el-radio v-for="(item, index) in sfList" :key="index" :label="item.id">{{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="form.limitUser ==0 "
            label="是否需要开户"
            prop="limitOpenAccount"
          >
            <el-radio-group v-model="form.limitOpenAccount">
              <el-radio v-for="(item, index) in sfList" :key="index" :label="item.id">{{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="form.limitUser ==0 "
            label="是否限制部门"
            prop="limitDept"
          >
            <el-radio-group v-model="form.limitDept" :disabled="isDisableStatus.limitDept">
              <el-radio v-for="(item, index) in limitList" :key="index" :label="item.id">{{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </section>
        <section class="join-conditions-content">
          <p class="title">红包设置</p>
          <el-form-item label="用户子账户" prop="userSubAccount">
            <!--            <el-input v-model="form.userSubAccount" placeholder="请输入职工福利子账号"/>-->
            <el-select
              v-model="form.userSubAccount"
              :disabled="state!='create'"
              placeholder="请选择"
              style="width: 100%"
              @change="handleAccountChange"
            >
              <el-option
                v-for="(item, index) in accountList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="单个用户每日领红包次数上限"
            prop="drawEverydayToplimit"
          >
            <el-input-number
              v-model="form.drawEverydayToplimit"
              :min="0"
              :max="999999999"
              :step="1"
              step-strictly
              :disabled="checkForm.drawEverydayToplimit"
              label="请设置单个用户每日领红包次数上限"
            />
            <el-checkbox v-model="checkForm.drawEverydayToplimit" style="margin-left: 30px;">不限制</el-checkbox>
          </el-form-item>
          <el-form-item
            label="单个用户在整个活动中领取红包上限"
            prop="winActivityToplimit"
          >
            <el-input-number
              v-model="form.winActivityToplimit"
              :min="0"
              :max="999999999"
              :step="1"
              step-strictly
              label="请设置单个用户在整个活动中领取红包上限"
              :disabled="checkForm.winActivityToplimit"
            />
            <el-checkbox v-model="checkForm.winActivityToplimit" style="margin-left: 30px;">不限制</el-checkbox>
          </el-form-item>
          <el-form-item label="出金账户" prop="accountId">
            <el-select
              v-model="form.accountId"
              :disabled="state!='create'"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in accList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </section>
        <el-form-item label="活动说明" prop="content">
          <tinymce v-if="showTinymce" v-model="form.content" :height="300" />
        </el-form-item>
      </el-form>
    </section>

    <div class="manage-footer">
      <el-button style="padding: 8px 30px;" @click="handleCancel">取消</el-button>
      <el-button style="padding: 8px 30px;" type="primary" @click="handleSubmit">确定</el-button>
    </div>
  </section>
</template>
<script>

import {
  getAcc, getDictByCode, insert,
  update,
  get,
  getAccountList
} from '@/views/activity/redPacket/api/index'
import CryptoJS from '@/utils/aesJiaJM'

export default {
  name: 'RedPacketActivityManage',
  components: {},
  data() {
    return {
      state: 'create',
      formloading: false,
      form: {
        id: '',
        title: '',
        activityType: '',
        coverId: '',
        time: [],
        activityStartDatetime: '',
        activityEndDatetime: '',
        totalCopies: 1,
        onceAmountMini: '',
        onceAmountMax: '',
        receiveExpiresDatetime: '',
        lastExpiresDatetime: '',
        limitAuth: 0,
        limitOpenAccount: 0,
        limitDept: 0,
        limitUser: 0,
        userSubAccount: '',
        drawEverydayLimit: 0,
        drawEverydayToplimit: '',
        winActivityLimit: 0,
        winActivityToplimit: '',
        accountId: '',
        content: '',
        publishStatus: 'RPAPUBSTATUS0'
      },
      checkForm: {
        totalCopies: false,
        onceAmountMax: false,
        receiveExpiresDatetime: false,
        lastExpiresDatetime: false,
        drawEverydayToplimit: false,
        winActivityToplimit: false
      },
      rules: {
        title: [{
          required: true,
          message: '请输入活动名称',
          trigger: 'blur'
        },
        {
          min: 1,
          max: 100,
          message: '长度在 1 到 100 个字符',
          trigger: 'blur'
        }
        ],
        activityType: [{
          required: true,
          message: '请选择活动类型',
          trigger: 'change'
        }],

        coverId: [{
          required: true,
          message: '请设置封面图片',
          trigger: 'blur'
        }],
        time: [{
          required: true,
          message: '请选择使用时间',
          trigger: 'blur'
        }],
        totalCopies: [{
          required: true,
          message: '请设置红包总份数',
          trigger: 'blur'
        }],
        onceAmountMini: [{
          required: true,
          message: '请设置红包最小金额',
          trigger: 'blur'
        }],
        onceAmountMax: [{
          required: true,
          message: '请设置红包最大金额',
          trigger: 'blur'
        }],

        /* receiveExpiresDatetime: [{
           required: true,
           message: '请设置红包领取失效时间',
           trigger: 'blur'
         }],*/
        lastExpiresDatetime: [{
          required: true,
          message: '请设置红包失效时间',
          trigger: 'blur'
        }],
        limitAuth: [{
          required: true
        }],
        limitOpenAccount: [{
          required: true
        }],
        limitDept: [{
          required: true
        }],
        limitUser: [{
          required: true
        }],
        userSubAccount: [{
          required: true,
          message: '请输入用户子账户',
          trigger: 'blur'
        }],
        accountId: [{
          required: true,
          message: '请选择出金账户',
          trigger: 'blur'
        }],
        content: [{
          required: true,
          message: '请输入活动内容',
          trigger: 'blur'
        }],
        drawEverydayToplimit: [{
          required: true,
          message: '请输入单个用户每日领红包次数上限',
          trigger: 'blur'
        }],
        winActivityToplimit: [{
          required: true,
          message: '请输入单个用户在整个活动中领取红包上限',
          trigger: 'blur'
        }],
        drawEverydayLimit: [{
          required: true
        }],
        winActivityLimit: [{
          required: true
        }]
      },
      dict: {
        REDPACT: []
      },
      uploadImg: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      sfList: [
        {
          name: '否',
          id: 0
        }, {
          name: '是',
          id: 1
        }
      ],
      limitList: [
        {
          name: '不限制',
          id: 0
        }, {
          name: '限制',
          id: 1
        }
      ],
      accList: [], // 出金账户
      accountList: [], // 用户子账号列表
      isDisableStatus: {
        limitUser: false,
        limitDept: false
      },
      showTinymce: false

    }
  },
  async created() {
    this.state = this.$route.query.type === 'c' ? 'create' : 'update'
    if (this.$route.query.type === 'u') {
      if (this.$route.query.i) {
        this.getData(this.$route.query.i)
      } else {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    } else {
      this.showTinymce = true
    }
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.accList = await this.getAccFun()
    this.accountList = await this.getAccountList()
  },
  methods: {

    /**
     * 选择用户子账户
     * */
    handleAccountChange(value) {
      const obj = this.accountList.find(a => a.subAcntTp === value)
      this.$alert(`您选择的用户子账户是：${obj.subAcntNm}，状态为：${obj.subAcntSt === 1 ? '禁用' : '启用'}，
        ${obj.subAcntStartTm ? '有效期是：' + this.formatTime(obj.subAcntStartTm) + '至' : ''}
        ${obj.subAcntEndTm ? this.formatTime(obj.subAcntEndTm) + ']' : ''}`, '提示', {
        confirmButtonText: '确定'
      })
    },
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0]
            .list : []
        }).catch(error => {
          reject(error)
        })
      })
    },
    formatTime(str) {
      return str && str.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3 $4:$5:$6')
    },
    /**
     * 获取出金账户
     * */
    getAccFun() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getAcc().then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.name}(${CryptoJS.$aesJieM(a.accountNumber)})`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    /**
     * 获取用户子账号
     * */
    getAccountList() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getAccountList().then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.subAcntTp,
            label: `${a.subAcntTp}-${a.subAcntNm}[${a.subAcntSt === 1 ? '禁用' : '启用'}]${a.subAcntStartTm ? '[' + this.formatTime(a.subAcntStartTm) + '至' : ''}${a.subAcntEndTm ? this.formatTime(a.subAcntEndTm) + ']' : ''}`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    handleSubmit() {
      this.state === 'create' ? this.createData() : this.updateData()
    },

    handleCancel() {
      this.$router.back()
    },

    setInfo() {
      this.form.totalCopies = this.checkForm.totalCopies ? -1 : this.form.totalCopies
      this.form.onceAmountMax = this.checkForm.onceAmountMax ? this.form.onceAmountMini : this.form.onceAmountMax
      this.form.receiveExpiresDatetime = this.checkForm.receiveExpiresDatetime ? -1 : this.form.receiveExpiresDatetime
      this.form.lastExpiresDatetime = this.checkForm.lastExpiresDatetime ? '2038-01-01 00:00:00' : this.form.lastExpiresDatetime
      this.form.drawEverydayToplimit = this.checkForm.drawEverydayToplimit ? -1 : this.form.drawEverydayToplimit
      this.form.drawEverydayLimit = this.checkForm.drawEverydayToplimit ? 0 : 1
      this.form.winActivityToplimit = this.checkForm.winActivityToplimit ? -1 : this.form.winActivityToplimit
      this.form.winActivityLimit = this.checkForm.winActivityToplimit ? 0 : 1
    },
    /*
     * 新增
     * */
    createData() {
      this.setInfo()
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          params['activityStartDatetime'] = params.time && params.time.length > 0 ? params.time[0] : ''
          params['activityEndDatetime'] = params.time && params.time.length > 0 ? params.time[1] : ''
          delete params['time']
          return new Promise((resolve, reject) => {
            insert(params).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 1500
              })
              this.$router.back()
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },

    /**
     * 编辑提交
     */
    updateData() {
      this.setInfo()
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = {
            ...this.form
          }
          params['activityStartDatetime'] = params.time && params.time.length > 0 ? params.time[0] : ''
          params['activityEndDatetime'] = params.time && params.time.length > 0 ? params.time[1] : ''
          delete params['time']
          return new Promise((resolve, reject) => {
            update(params).then(() => {
              loading.close()
              this.$message({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.$router.back()
            }).catch(error => {
              reject(error)
              loading.close()
            })
          })
        }
      })
    },

    /**
     * 获取详情
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id }).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
            if (key === 'time') {
              if (data['activityStartDatetime'] && data['activityEndDatetime']) {
                this.form[key] = [data['activityStartDatetime'], data['activityEndDatetime']]
              }
            } else {
              this.form[key] = data[key]
            }
          }
          this.uploadImg.viewId = data.coverId
          // 总份数
          this.checkForm.totalCopies = this.form.totalCopies === -1
          // 红包最大金额
          this.checkForm.onceAmountMax = this.form.onceAmountMax === this.form.onceAmountMini
          // 红包领取的失效时间
          this.checkForm.receiveExpiresDatetime = this.form.receiveExpiresDatetime === -1
          // 红包最终失效时间
          this.checkForm.lastExpiresDatetime = this.form.lastExpiresDatetime === '2038-01-01 00:00:00'
          // 单个用户每日领红包次数上限
          this.checkForm.drawEverydayToplimit = this.form.drawEverydayLimit === 0
          // 单个用户在整个活动中领取红包上限
          this.checkForm.winActivityToplimit = this.form.winActivityLimit === 0
          // 已经设置了人员的话，不可编辑更改;已经设置了部门的话，不可编辑更改
          this.isDisableStatus.limitDept = data.limitDeptFlag === 1
          this.isDisableStatus.limitUser = data.limitUserFlag === 1
          this.showTinymce = true
          console.log(this.form)
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    }
  }
}
</script>
<style lang="scss">

.red-packet-activity-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 8px;
      /*对垂直流动条有效*/
      height: 1px;
      /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    &:hover {
      overflow: auto;
    }
  }

  .main-form {
    width: 1000px !important;
    margin: 0 auto;

    .line {
      text-align: center;
    }

    .form-card {
      margin-top: 20px;

      .el-card__body {
        max-width: 90%;
        margin: 0 auto;
      }
    }

    .coupon-num input {
      text-align: left;
    }

    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;

      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }

    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
      margin-bottom: 10px;
    }

    .tip {
      @include font-color($mainColor);
      font-size: 14px;
      padding-left: 250px;
      margin-top: 0;
    }

    .join-conditions-content {
      border: 1px dashed #eee;
      padding: 10px;
      margin-bottom: 20px;

      .title {
        vertical-align: middle;
        font-size: 16px;
        color: #606266;
        line-height: 40px;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        margin: 0;
        font-weight: 700;
      }
    }

  }

  .manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
